package java_thinking.unit_10._10_8;

/**
 * @Description : 闭包与回调案例
 * @author: cww
 * @DateTime: 2019/3/13 8:34
 */
interface Incrementable1 {
    void increment();
}

class CalleerA implements Incrementable1{

    private int i = 0;
    @Override
    public void increment() {
        i++;
        System.out.println("CallerA.increment i="+i);
    }
}

class MyIncrement1{
    void increment(){
        System.out.println("MyIncrement1.increment");
    }
    static void f(MyIncrement1 myIncrement1){
        myIncrement1.increment();
    }
}

/**
 * 在Caller2中实现一个内部类回调Caller2.increment,要求这个内部类是Incrementable接口的实现
 */
class Calleer2 extends MyIncrement1{
    private int i = 0;
    void increment(){
        super.increment();
        i++;
        System.out.println("Calleer2.increment");
    }

    private class Closure implements Incrementable1{

        @Override
        public void increment() {
            Calleer2.this.increment();
        }
    }
    Incrementable1 getClosure(){
        return new Closure();
    }
}



class ClosePackage{
    private Incrementable1 incrementable1;
    ClosePackage(Incrementable1 inc){
        incrementable1 = inc;
    }
    void go(){
        incrementable1.increment();
    }

    public static void main(String[] args) {
        //1.最简单的创建一个接口对象并调用的写法
        CalleerA calleer1 = new CalleerA();
        ClosePackage closePackage1 = new ClosePackage(calleer1);
        closePackage1.go();


        MyIncrement1 calleer2 = new Calleer2();
        calleer2.increment();
        //如果没有实现Caller2的内部类，这里则无法使用ClosePackage.go()
        ClosePackage closePackage2 = new ClosePackage(((Calleer2) calleer2).getClosure());
        closePackage2.go();
    }
}
